Whenever you use new, you should always use delete to free up the memory when you are done using the memory. And, whenever you use 'new []', you need to use 'delete []'. What that means is: when you use "new []" to create an array, then when you delete, you use 'delete []' to delete the whole array. On the other hand, if you just use "new" to dynamically create some memory, then you just use "delete". In addition, the number of new's should equal the number of delete's.
The reason you need brackets to delete arrays is because a pointer to an array looks like this:
Code:
className** p-------->className*
className*
className*
If you only use delete, then you will only delete the first line. When you use delete[], that command is programed to delete all the memory.
And if i do this ??
char c = new char[20];
delete c; // instead of delete [] c
is it an error ??
No. The compiler has no idea that's not what you intended. After all, you could be deleting the rest of the memory later.
I tried also to create an array of pointers to objects and verify that delete []
calls actually the destructors of all objects in the array before
deleting the array itself
In order to do that i put a printf in the class' destructor,but it wasn't displayed
Examine the output from this program:
Code:
#include <iostream>
using namespace std;
class Apple
{
public:
~Apple()
{
cout<<"Apple object destroyed"<<endl;
}
};
int main()
{
Apple** ptr = new Apple*[3];
for(int i = 0; i<3; i++)
{
ptr[i] = new Apple;
}
for(i=0; i<3; i++)
{
delete ptr[i]; //ptr[i] does not point to an array.
//ptr[i] points to a single Apple object.
}
delete [] ptr;
return 0;
}
output:
Apple object destroyed
Apple object destroyed
Apple object destroyed
Press any key to continue